//
// Created by 49647 on 2023/9/30.
//

#include "OmxCompBase.h"
#include <iostream>
#include "OmxCompEnc.h"
#include "OmxCompDec.h"

OmxCompBase::OmxCompBase() {
    printf("OmxCompBase::OmxCompBase\n");
    OMX_COMPONENTTYPE::SendCommand =
            [](OMX_HANDLETYPE hComponent, OMX_COMMANDTYPE Cmd, OMX_U32 nParam1, OMX_PTR pCmdData) {
                // 从OMX_COMPONENTTYPE* static_cast 到OmxCompBase*时会发生一个虚表指针的偏移量。
                auto *base = static_cast<OmxCompBase *>(reinterpret_cast<OMX_COMPONENTTYPE *>(hComponent));
                return base->SendCommand(Cmd, nParam1, pCmdData);
            };
}

OmxCompBase::~OmxCompBase() {
    printf("OmxCompBase::~OmxCompBase\n");
}

extern "C" {
OMX_ERRORTYPE OMX_APIENTRY OMX_GetHandle(
        OMX_OUT OMX_HANDLETYPE *pHandle,
        OMX_IN  OMX_STRING cComponentName,
        OMX_IN  OMX_PTR pAppData,
        OMX_IN  OMX_CALLBACKTYPE *pCallBacks) {
    printf(">> OMX_GetHandle\n");
    OmxCompBase *base;
    if (cComponentName) {
        base = new OmxCompEnc();
    } else {
        base = new OmxCompDec();
    }
    *pHandle = static_cast<OMX_COMPONENTTYPE *>(base);  // 返回的一定要是OMX_COMPONENTTYPE指针
    printf("<< OMX_GetHandle, OmxCompBase* = %p, OMX_COMPONENTTYPE* = %p\n", base, *pHandle);
    return OMX_ErrorNone;
}

OMX_ERRORTYPE OMX_APIENTRY OMX_FreeHandle(
        OMX_IN  OMX_HANDLETYPE hComponent) {
    printf("OMX_FreeHandle\n");
    auto *base = static_cast<OmxCompBase *>(reinterpret_cast<OMX_COMPONENTTYPE *>(hComponent));
    // 要从OmxCompBase指针去delete因为它的析构函数是虚的，而OMX_COMPONENTTYPE的析构不是虚的
    delete base;
    return OMX_ErrorNone;
}
}